<?php

namespace App\Http\Controllers\Api;

use App\Http\Services\FeieyunService;
use App\Models\Member;
use App\Models\MemberLabel;
use App\Models\Order;
use App\Models\Printer\PrinterTask;
use App\Models\Printer\PrinterTaskContent;
use App\Models\PrinterTaskOrder;
use App\Models\Product;
use App\Repositories\OrderRepository;
use Illuminate\Support\Facades\DB;

/**
 * 定时任务
 * @package
 */
class CronController extends MiniAppController
{

    /**
     * @var
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 打印任务
     */
    public function printer_task()
    {
        $taskList = PrinterTask::query()->where(['status' => 1])->get(['id', 'printer_sn', 'printer_type'])->toArray();

        if (empty($taskList) || count($taskList) == 0) {
            return false;
        }

        foreach ($taskList as $k => $task) {
            if (PrinterTaskContent::query()->where(['task_id' => $task['id'], 'status' => 0])->count("id") == 0) {
                PrinterTask::query()->where(['id' => $task['id']])->update(['status' => 2]);
                continue;
            }

            $contents = PrinterTaskContent::query()
                ->where([
                    'task_id' => $task['id'],
                    'status' => 0
                ])
                ->orderBy("id", "desc")
                ->get(['id', 'content', 'printer_id'])
                ->toArray();

            $feie = new FeieyunService(['id' => $task['printer_sn']]);
            foreach ($contents as $sk => $sv) {
                if (!PrinterTaskContent::query()->where(['id' => $sv['id'], 'status' => 0])->count("id"))
                    continue;
                if ($task['printer_type'] == 2) {//品单
                    $res = $feie->printLabelMsg($sv['content'], 1);
                } else { //订单/汇总单
                    $res = $feie->printMsg($sv['content'], $task['order_id']);
                }

                if ($res) {
                    PrinterTaskContent::query()->where("id", $sv['id'])->update(['status' => 1]);
                    PrinterTask::query()->where("id", $task['id'])->increment("print_amount");
                }
            }
            if (PrinterTaskContent::query()->where(['task_id' => $task['id'], 'status' => 0])->count("id") == 0) {
                PrinterTask::query()->where(['id' => $task['id']])->update(['status' => 2]);
            }
        }
    }

    /**
     * 打印订单
     */
    public function print_order()
    {
        $taskList = PrinterTask::query()->where(['status' => 0])->get(['id', 'printer_sn', 'printer_type', 'supplier_id'])->toArray();
        if (empty($taskList) || count($taskList) == 0) {
            return false;
        }

        foreach ($taskList as $k => $task) {

            if (PrinterTaskOrder::query()->where(['task_id' => $task['id'], 'status' => 0])->count("id") == 0) {
                PrinterTaskOrder::query()->where(['id' => $task['id']])->update(['status' => 1]);
                continue;
            }

            $contents = PrinterTaskOrder::query()->where(['task_id' => $task['id'], 'status' => 0])->orderBy("id", "desc")->get(['id', 'order_id'])->toArray();

            foreach ($contents as $sk => $sv) {
                $redis_key = "taskContent_" . $sv['id'];
                if (!empty(getRedisByKey($redis_key))) {
                    continue;
                }

                if (!PrinterTaskOrder::query()->where(['id' => $sv['id'], 'status' => 0])->count("id"))
                    continue;

                setRedisByDb($redis_key, 1);

                $res = (new OrderRepository())->printerOrder([
                    'orderId' => $sv['order_id'],
                    'shop_id' => $task['supplier_id'],
                    'task_id' => $task['id'],
                    'printer_id' => $task['printer_sn'],
                ], $task['printer_sn'], 2);

                if ($res) {
                    PrinterTaskOrder::query()->where("id", $sv['id'])->update(['status' => 1]);
                    PrinterTask::query()->where("id", $task['id'])->increment("print_amount");
                }

                delRedis($redis_key);
            }

            if (PrinterTaskOrder::query()->where(['task_id' => $task['id'], 'status' => 0])->count("id") == 0) {
                PrinterTask::query()->where(['id' => $task['id']])->update(['status' => 2]);
            }

        }
    }

    /**
     * 取消订单
     */
    public function cancel_order()
    {
        $orderIds = Order::query()->where(['status' => 1, 'order_source' => 0])
            ->where("create_time", '<', strtotime("-20 minute"))
            ->pluck("id")
            ->toArray();

        if ($orderIds) {
            foreach ($orderIds as $k => $orderId) {
                Order::query()->where("id", $orderId)->update([
                    'status' => 80
                ]);
            }
        }

//        $this->async_product();
        //发送通知---配送员
        (new OrderRepository())->sendSmsToDeliver();
    }

    public function auto_accept()
    {
        //自动接单
        (new OrderRepository())->autoAcceptOrders();
        return true;
    }

    /**
     * 同步数据
     */
    public function async_data()
    {

        $memberList = Member::query()->where("type", ">", 0)->get(['id', 'type'])->toArray();
        $roleList = [];  //同步角色
        foreach ($memberList as $k => $v) {
            $roleList[] = [
                'type' => $v['type'],
                'uid' => $v['id'],
                'create_time' => date("Y-m-d H:i:s"),
                'update_time' => date("Y-m-d H:i:s"),
            ];
        }
        MemberLabel::insert($roleList);

    }

    public function async_product()
    {
        $productList = Product::query()
            ->join("supplier as s", 's.id', 'product.shop_id')
            ->orderBy("product.id", "ASC")
            ->get(['product.id', 's.name', 'product.shop_id'])
            ->toArray();

        $productList = ass_column($productList, 'shop_id', true);
        foreach ($productList as $k => $products) {
            $sequence = 100000;
            $sql = "";
            foreach ($products as $sk => $v) {
                $sequence++;
                $sql = "update wx_product set `sn`='" . ($v['name'] . $sequence) . "',`sequence`={$sequence} where id={$v['id']};";
                if ($sql) {
                    DB::update(DB::raw($sql));
                }
            }
        }
    }

}
